import { getCurrentInstance, createVNode, render, provide, inject } from 'vue';
import { cloneDeep } from 'lodash';

// 为每个模态框创建唯一的上下文key
const createModalContextKey = () => Symbol('modal-context-' + Date.now() + '-' + Math.random());

// 存储所有打开的模态框
const modalStack = new Map();

export const useModal = () => {
  const instance = getCurrentInstance();
  
  const getContext = () => {
    if (!instance) {
      throw new Error('useModal must be used within a component');
    }
    return instance.appContext;
  };

  const openModal = (component, props = {}) => {
    return new Promise((resolve, reject) => {
      const context = getContext();
      const container = document.createElement('div');
      const modalId = Date.now() + '-' + Math.random();
      const contextKey = createModalContextKey();
      
      // 创建模态框上下文
      const modalContext = {
        id: modalId,
        props: cloneDeep(props),
        resolve,
        reject,
        close: () => {
          close();
          resolve(null);
        },
        confirm: (data) => {
          close();
          resolve(data || true);
        },
        cancel: () => {
          close();
          reject(new Error('cancelled'));
        }
      };

      // 清理函数
      const close = () => {
        render(null, container);
        document.body.removeChild(container);
        modalStack.delete(modalId);
      };

      // 创建包装组件，确保每个模态框有独立的上下文
      const WrapperComponent = {
        setup() {
          provide(contextKey, modalContext);
          return () => createVNode(component, modalContext.props);
        }
      };

      // 创建vnode
      const vnode = createVNode(WrapperComponent);
      vnode.appContext = context;

      // 存储模态框信息
      modalStack.set(modalId, {
        container,
        context: modalContext,
        contextKey,
        close
      });

      // 添加到body并渲染
      document.body.appendChild(container);
      render(vnode, container);
    });
  };

  return {
    openModal
  };
};

// 在模态框组件内部使用的hook
export const useModalContext = () => {
  // 查找当前组件对应的上下文
  let context = null;
  
  // 遍历所有打开的模态框，找到匹配的上下文
  for (const [id, modalInfo] of modalStack) {
    try {
      const ctx = inject(modalInfo.contextKey);
      if (ctx) {
        context = ctx;
        break;
      }
    } catch (e) {
      // 忽略注入错误，继续查找
    }
  }
  
  if (!context) {
    throw new Error('useModalContext must be used within a modal component opened by useModal');
  }

  return {
    modalProps: context.props,
    confirm: context.confirm,
    cancel: context.cancel,
    close: context.close
  };
};